package com.sheep.exception.handler.handler;

import com.sheep.exception.handler.constant.CodeMsg;
import com.sheep.exception.handler.exception.BusinessException;
import com.sheep.exception.handler.model.ResResultDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Usage                : 全局异常处理程序
 * Project name         :
 * Author               : lizy4
 * Mail                 : 760470497@qq.com
 * Date                 : 2021/01/12
 * Version              : 1.0.0
 * Modification history :
 * Date          Author          Version          Description
 * ---------------------------------------------------------------
 * 2021/01/12       lizy4             1.0.0             新建
 *
 */
@Slf4j
@ControllerAdvice
public class GloabExceptionHandler {
	@ResponseBody
	@ExceptionHandler(Exception.class)
    public ResResultDto handleConstraintViolationException(Exception e) {
        log.error("系统处理错误：",e);
        ResResultDto res = new ResResultDto();
        res.setCode(ResResultDto.CODE_ERROR);
        res.setStatus(ResResultDto.STATUS_ERROR);
        res.setMsg("系统处理错误");
	    if(e instanceof BusinessException){
            BusinessException baseException = (BusinessException) e;
            res.setCode(baseException.getCode());
            res.setMsg(baseException.getMsg());
        } else if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException baseException = (MethodArgumentNotValidException) e;
            res.setCode(CodeMsg.BIND_ERROR.getCode());
            res.setMsg(baseException.getBindingResult().getFieldError().getDefaultMessage());
        }
        return res;
    }
}
